package com.kfm.springboot.aspect;

import com.kfm.springboot.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class LogAspect {

    @Pointcut("execution(* com.kfm.springboot.controller.*.*(..))")
    public void pt(){}


    @Around("pt()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) {
        Object returnValue = null;
        // 获取 request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = IPUtils.getIpAddr(request);

        Signature signature = proceedingJoinPoint.getSignature();
        // 请求的类
        Class declaringType = signature.getDeclaringType();
        // 请求的方法
        String name = signature.getName();
        //  请求的参数
        Object[] args = proceedingJoinPoint.getArgs();

        log.info("{}: 请求了 {}.{} 方法, 参数是: {}", ip, declaringType.getName(), name, Arrays.toString(args));

        try {
            // 执行方法
            returnValue = proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return returnValue;
    }
}
